import './Home.less';
import { Input } from 'antd';
import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux'
import { setGlobalValue } from '@/store/action'
import { store } from '@/store/index';
import PubSub from 'pubsub-js'

function Subhome(props) {
    const handleChange = (e) => {
        props.onInputValueChange(e.target.value)
    }
    return (
        <Input className='customInput' value={props.inputValue} onChange={handleChange} />
    );
}

function Home() {
    const dispatch = useDispatch();
    let initValue = store.getState().value;
    let userInfo = store.getState().user;
    let [val, setVal] = useState(initValue);
    let [user, setUser] = useState(userInfo);
    
    const handleChangeGlobal = (val) => {
        setVal(val)
        dispatch(setGlobalValue(val))
    }

    useEffect(() => {
        const sub = PubSub.subscribe('updateUserInfo', (msg, data) => {
            setUser(data)
        })
        return () => {
            PubSub.unsubscribe(sub)
        }
    })

    return (
        <div className="App">
            当前用户：<br/>
            姓名：{user.name}<br/>
            年龄：{user.age}<br/>
            <Subhome inputValue={val} onInputValueChange={handleChangeGlobal} />
        </div>
    );
}

export default Home;